package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.properties.MinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * @Author:lyd
 **/
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties minioProperties;

    @Override
    public String fileUpload(MultipartFile file) throws Exception {


        //1、判断桶是否存在
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if (!found) {
            //2、不存在则创建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        } else {
            log.info("桶已经存在！");
        }
        //3、上传文件
        //3、1文件名防重复，文件夹归档
        String fileFormat = DateUtil.formatDate(new Date(), "yyyy/MM/dd");
        String fileName = fileFormat + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "_" + file.getOriginalFilename();
        minioClient.putObject(
                PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        //4、返回文件访问路径
        return String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), fileName);
    }
}
